<template>
  <div>
    <el-dialog
      :title="title"
      :close-on-click-modal="false"
      :visible.sync="visible">
      <el-form
        :model="inputForm"
        ref="inputForm"
        v-loading="loading"
        :class="method==='view'?'readonly':''"
        :disabled="method==='view'"
        label-width="120px">

        <el-row :gutter="15">
          <!-- 能源类型 -->
          <el-col :span="12">
            <el-form-item label="能源类型" prop="energyCategoryId">
              <select-tree
                v-if="method !== 'view'"
                v-model="inputForm.energyCategoryId"
                :data="energyCategoryList"
                :props="{ value: 'id', label: 'name', children: 'children' }"
                placeholder="请选择能源类型"
                @getValue="handleEnergyCategoryChange"
                style="width: 100%;"
              />
              <el-input
                v-else
                v-model="energyCategoryName"
                disabled
                placeholder="无数据"
              />
            </el-form-item>
          </el-col>

          <!-- 表具 -->
          <el-col :span="12">
            <el-form-item label="表具" prop="meterId">
              <el-select
                v-if="method !== 'view'"
                v-model="inputForm.meterId"
                placeholder="请选择表具"
                style="width: 100%;"
                @change="handleMeterChange"
                filterable
                clearable>
                <el-option
                  v-for="item in meterList"
                  :key="item.id"
                  :label="`${item.meterName} (${item.meterCode})`"
                  :value="item.id">
                  <span style="float: left">{{ item.meterName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">
                    {{ item.meterCode }}
                  </span>
                </el-option>
              </el-select>
              <el-input
                v-else
                v-model="meterName"
                disabled
                placeholder="无数据"
              />
            </el-form-item>
          </el-col>

          <!-- 读数 -->
          <el-col :span="12">
            <el-form-item label="本期读数" prop="readingValue">
              <el-input
                v-model="inputForm.readingValue"
                :placeholder="inputForm.meterId ? '本期读数(' + unit + ')' : '请填写读数'" />
            </el-form-item>
          </el-col>

          <!-- 抄表时间 -->
          <el-col :span="12">
            <el-form-item label="抄表时间" prop="readingTime">
              <el-date-picker
                v-model="inputForm.readingTime"
                type="datetime"
                placeholder="请选择抄表时间"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%;" />
            </el-form-item>
          </el-col>

          <!-- 抄表方式 -->
          <el-col :span="12">
            <el-form-item label="抄表方式" prop="sourceType">
              <el-select
                v-model="inputForm.sourceType"
                placeholder="请选择"
                style="width: 100%;">
                <el-option
                  v-for="item in $dictUtils.getDictList('meter_record_type')"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>

          <!-- 抄表人 -->
          <el-col :span="12">
            <el-form-item label="抄表人" prop="recorder">
              <el-input
                v-model="inputForm.recorder"
                placeholder="请填写抄表人" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false">关闭</el-button>
        <el-button
          type="primary"
          v-if="method !== 'view'"
          @click="doSubmit()"
          v-noMoreClick>
          确定
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import SelectTree from '@/components/treeSelect/treeSelect.vue'

export default {
  components: { SelectTree },
  data () {
    return {
      title: '',
      method: '',
      visible: false,
      loading: false,
      energyCategoryList: [],
      meterList: [],
      unit: '',
      energyCategoryName: '',
      meterName: '',
      inputForm: {
        id: '',
        energyCategoryId: '',
        meterId: '',
        readingValue: '',
        readingTime: '',
        sourceType: '',
        recorder: ''
      }
    }
  },
  created () {
    this.loadEnergyCategoryList()
  },
  methods: {
    // 加载能源分类
    loadEnergyCategoryList () {
      this.$http({
        url: '/energy/energyCategory/list',
        method: 'get'
      }).then(({ data }) => {
        this.energyCategoryList = data.list || []
      })
    },

    // 能源分类切换 → 加载表具
    handleEnergyCategoryChange (id, label, node) {
      this.inputForm.meterId = ''
      this.unit = ''
      this.meterList = []

      if (id) {
        this.$http({
          url: '/energy/meter/list',
          method: 'post',
          data: { energyCategory: { id } }
        }).then(({ data }) => {
          if (data && data.success) {
            this.meterList = data.page?.list || []
            if (this.meterList.length === 0) {
              this.$message.warning('该能源类型下没有可用的表具')
            }
          } else {
            this.$message.error(data?.msg || '获取表具数据失败')
          }
        }).catch(() => {
          this.$message.error('获取表具数据异常')
        })
      }
    },

    // 表具切换 → 设置单位
    handleMeterChange (meterId) {
      if (meterId) {
        const selectedMeter = this.meterList.find(item => item.id === meterId)
        if (selectedMeter) {
          this.unit = selectedMeter.unit || ''
          this.$set(this.inputForm, 'meterId', meterId)
        }
      } else {
        this.unit = ''
      }
    },

    // 初始化表单
    init (method, id) {
      this.method = method
      this.inputForm.id = id || ''

      if (method === 'add') {
        this.title = '新建用能登记'
        // 初始化
        this.inputForm = {
          id: '',
          energyCategoryId: '',
          meterId: '',
          readingValue: '',
          readingTime: '',
          sourceType: '',
          recorder: ''
        }
        this.meterList = []
        this.unit = ''
      } else if (method === 'edit') {
        this.title = '修改用能登记'
      } else if (method === 'view') {
        this.title = '查看用能登记'
      }

      this.visible = true
      this.loading = false

      this.$nextTick(() => {
        if (method === 'edit' || method === 'view') {
          this.$refs.inputForm.resetFields()
          this.loading = true
          this.$http({
            url: `/energy/meterRecord/queryById?id=${this.inputForm.id}`,
            method: 'get'
          }).then(({ data }) => {
            this.inputForm = this.recover(this.inputForm, data.meterRecord)
            this.unit = data.meterRecord.unit || ''
            
            // 设置能源类型名称
            this.energyCategoryName = data.meterRecord.energyCategoryName || ''
            
            // 设置表具名称
            this.meterName = data.meterRecord.meterName || ''
            if (data.meterRecord.meterCode) {
              this.meterName += ` (${data.meterRecord.meterCode})`
            }

            if (this.inputForm.energyCategoryId) {
              this.$http({
                url: '/energy/meter/list',
                method: 'post',
                data: { energyCategory: { id: this.inputForm.energyCategoryId } }
              }).then(({ data }) => {
                this.meterList = data.page?.list || []
                this.loading = false
              })
            } else {
              this.loading = false
            }
          })
        }
      })
    },

    // 表单提交
    doSubmit () {
      this.$refs['inputForm'].validate((valid) => {
        if (valid) {
          this.loading = true
          this.$http({
            url: `/energy/meterRecord/save`,
            method: 'post',
            data: this.inputForm
          }).then(({ data }) => {
            if (data && data.success) {
              this.visible = false
              this.$message.success(data.msg)
              this.$emit('refreshDataList')
            }
            this.loading = false
          })
        }
      })
    }
  }
}
</script>
